package com.itbaizhan.utils;

/**
 * @author spf
 * @date 2024/2/13
 * @time 15:19
 */

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;

/**
 * JWT 工具类
 */
public class JWTUtils {
    // 签发人
    public static final String ISSUER = "baizhan";
    // 密钥
    public static final String SECRET_KEY = "sdjslfg-=<>rjkel";
    // 过期时间
    public static final long TOKEN_EXPIRE_TIME = 5 * 60 * 1000;
    // 生成token
    public static String token(String username){
        String token = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(new Date())
                .withSubject(username)
                .withExpiresAt(new Date(new Date().getTime() + TOKEN_EXPIRE_TIME))
                .sign(Algorithm.HMAC256(SECRET_KEY));

        return token;
    }

    // 验证token
    public static Boolean verify(String token){
        try {
            JWT.require(Algorithm.HMAC256(SECRET_KEY))
                    .withIssuer(ISSUER)
                    .build()
                    .verify(token);

            return true;
        } catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
